import os
import system

if system.IS_WINDOWS:
    SITE_PACKAGES = os.path.join('Lib', 'site-packages')
    ENV_BIN_DIR = os.path.join('Scripts')
    PYTHON_EXE = os.path.join(ENV_BIN_DIR, 'python.exe')
else:
    SITE_PACKAGES = os.path.join('lib', 'python' + system.PYTHON_VERSION, 'site-packages')    
    ENV_BIN_DIR = os.path.join('bin')        
    PYTHON_EXE = os.path.join(ENV_BIN_DIR, 'python')

# Can be changed at runtime and the locate_ functions pick it up
default_virtualenv_dir_name = 'virtualenv'
default_locate_virtualenv_search_dirs_up = 5
USE_DEFAULT = None # Use default value when None is passed as argument

def get_activate_script_path():
    return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'activate_virtualenv.py')

def is_active():
    return 'VIRTUAL_ENV' in os.environ

def locate_virtualenv(virtualenv_dir_name=USE_DEFAULT, num_dirs_up=USE_DEFAULT):
    if virtualenv_dir_name is None:
        virtualenv_dir_name = default_virtualenv_dir_name
    if num_dirs_up is None:
        num_dirs_up = default_locate_virtualenv_search_dirs_up
    base_path = os.path.dirname(os.path.abspath(__file__))
    relative_path = virtualenv_dir_name
    while num_dirs_up >= 0:        
        tested_path = os.path.abspath(os.path.join(base_path, relative_path))
        site_packages_path = os.path.join(tested_path, SITE_PACKAGES)
        python_exe_path = os.path.join(tested_path, PYTHON_EXE)
        if os.path.isdir(site_packages_path) and os.path.isfile(python_exe_path):
            return tested_path
        num_dirs_up = num_dirs_up - 1
        relative_path = os.path.join('..', relative_path)
        
def locate_site_packages_path(virtualenv_dir_name=USE_DEFAULT, num_dirs_up=USE_DEFAULT):
    virtualenv_path = locate_virtualenv(virtualenv_dir_name, num_dirs_up)
    return os.path.join(virtualenv_path, SITE_PACKAGES)

def locate_bin_path(virtualenv_dir_name=USE_DEFAULT, num_dirs_up=USE_DEFAULT):
    virtualenv_path = locate_virtualenv(virtualenv_dir_name, num_dirs_up)
    return os.path.join(virtualenv_path, ENV_BIN_DIR)

def locate_python_exe_path(virtualenv_dir_name=USE_DEFAULT, num_dirs_up=USE_DEFAULT):
    virtualenv_path = locate_virtualenv(virtualenv_dir_name, num_dirs_up)
    return os.path.join(virtualenv_path, PYTHON_EXE)
